var transaction = new liwe.module ( "transaction", { 'pp_response' : '_pp_response' } );

transaction._dest_div = null;
transaction._kind_list = null;

transaction.options = [ { 'label' : 'PayPal' , 'value' : 'PP' },
						{ 'label' : 'Bonifico', 'value' : 'BB' },
						{ 'label' : 'Alla consegna' , 'value' : 'CC' }
					  ]

transaction.init = function ()
{
	transaction.valid_events ( [ 'nolist', 'transaction_select', 'close', 'completed','pp_response'  ] );
	transaction.get_cfg ();
	transaction.load_templates ();
	transaction._get_cfg_try = 0;
};


//{{{transaction.render_transaction_list = function ( dest_div, module )
transaction.render_transaction_list = function ( dest_div, module )
{
	if ( typeof ( dest_div ) == "undefined" )	dest_div = transaction._dest_div;
	if ( typeof ( module ) == "undefined" )	module = "transaction";


	transaction.get_kind_list ( module, function ()
	{
		$( dest_div, String.formatDict ( transaction.templates [ 'SITE_TRANSACTION_BOX' ],  { 'module' : module } ) );
		transaction._make_list_form ( transaction._kind_list, module );
	} );
}
//}}}
//{{{transaction.get_kind_list = function ( module, cback )
transaction.get_kind_list = function ( module, cback )
{
	var get =  { 'action' : 'transaction.ajax.list_kind', 'visible' : 1, 'module' : module };

	transaction.ajax ( get, function ( resp )
	{
		liwe.types.to_list ( resp.kind );
		transaction._kind_list = resp.kind; 
		if ( cback ) cback( resp.kind );
		return
	});
	
}
//}}}
//{{{transaction._make_list_form  = function ( data, module )
transaction._make_list_form  = function ( data, module )
{
	if ( data.length == 0 )
	{
		transaction.dispatchEvent ( "nolist", null, { 'alert' : transaction.templates [ 'SITE_NOLIST' ] } );
		return;
	}
	liwe.types.to_list ( data );
	var options = []
    var f = new liwe.form.instance ( 'tr_kind_sellist_form' );
	f.hidden ( { name: "module", value: module } );
	data.iterate ( function ( item, k )
	{
		item [ '_charge' ] = '(' +  Money.fromLongInt ( item [ 'charge' ] ) +  ' &euro;)' ;
		var def_check = false
		var descr = String.formatDict ( transaction.templates [ 'SITE_OPTION_LIST' ], item );
		if ( k == 1 ) def_check = true
		var onclick_evt = "transaction.select_kind ( this," + item [ 'id_kind' ] + ");" 

		f.radio ( { label : "", name: "id_kind", 'value' : item [ 'id_kind' ], nonl : true, 
					onclick : onclick_evt  } );
		f.label ( { value : descr } );
		
	} );

	f.set ( 'transaction_sel_form' );
	f.set_value ( 'id_kind', 1 )	
	return;
}
//}}}
//{{{transaction.select_kind = function ( el, id_kind )
transaction.select_kind = function ( el, id_kind )
{
	var kind = transaction._get_kind  ( id_kind )
	var params = { 'kind' : kind };

	//ADD MODULE
	var f = liwe.form.get ( "tr_kind_sellist_form" );
	params [ 'module' ] =  f.get_value ( 'module' );

	//CALL EVENT
	transaction.dispatchEvent ( "transaction_select", null, params );
}
//}}}
//{{{transaction.box_close = function()
transaction.box_close = function()
{
	var f = liwe.form.get ( "tr_kind_sellist_form" );
	var params = f.get_values ();

	var id_kind = f.get_value ( 'id_kind' );
	var kind = transaction._get_kind  ( id_kind );
	params [ 'kind' ] = kind

	transaction.dispatchEvent ( "transaction_select", null, params );
	transaction.dispatchEvent ( "close", null, params );
}	
//}}}
//{{{transaction._get_kind = function  ( id_kind )
transaction._get_kind = function  ( id_kind )
{
	var kind = {};
	transaction._kind_list.iterate ( function ( el )
	{
		if ( el [ 'id_kind' ] == id_kind ) 
		{
			kind = el;	
		}
	} );
	liwe.types.to_dict ( kind );
	return kind;
};
//}}}
//{{{transaction.get_cfg = function ( cback )
transaction.get_cfg = function ( cback )
{
	transaction.ajax ( { action : 'transaction.ajax.get_cfg' } , function ( data )
			{
				transaction.cfg = data [ 'cfg' ];
				if ( cback ) cback ();
			} );
};
//}}}
//{{{transaction.send = function ( vals, sped, prods, transaction_id, module )
transaction.send = function ( vals, sped, prods, transaction_id, module )
{
	if ( typeof ( module ) == 'undefined' ) module = "transaction";

	var pp_custom = window [ module ].templates [ 'pp_custom' ];

	
	

	vals [ 'module' ] = module;
	if ( ! vals [ 'order_code' ] ) vals [ 'order_code' ] = 0;	

	var get = { 'action' : 'transaction.ajax.get_kind' , 'id_kind' : transaction_id };
	transaction.ajax ( get , function ( resp )
	{
		var kind =  resp.kind;
		if ( kind [ 'mode' ] == 'PP' )
		{
			transaction.send_paypal ( vals, prods, sped, pp_custom, module);
		} else {
			var params = { 'vals' : vals, 'prods' : prods, 'sped' : sped, 'transaction_kind' : kind , 'module' : module};
			transaction.dispatchEvent ( "completed", null, params );
		}
	});	
}
//}}} 
//{{{transaction.send_paypal = function ( vals, prods, sped, pp_custom )
transaction.send_paypal = function ( vals, prods, sped, pp_custom, module )
{
	if ( typeof ( pp_custom ) == 'undefined' ) pp_custom = transaction.templates [ 'pp_custom' ];
	var custom = String.formatDict ( pp_custom, vals );
	transaction._send_paypal ( vals, prods, sped, pp_custom, module );

	/*
	transaction.ajax ( { action: 'transaction.ajax.get_hash', custom: custom }, function ( res )
	{
		vals [ '_hash' ] = res [ 'hash' ];
	} );
	*/
};

transaction._send_paypal = function ( vals, prods, sped, pp_custom, module )
{
	if ( typeof ( pp_custom ) == 'undefined' ) pp_custom = transaction.templates [ 'pp_custom' ];

	var post = { "action" : "transaction.ajax.custom_get_url" };
	transaction.ajax ( post , function ( data )
	{
		if ( ! transaction.cfg )
		{
			transaction._get_cfg_try ++;

			if ( transaction._get_cfg_try > 5 )
			{
				alert ( "Si e verificato un problema durante la configurazione dell'ordine" );
				return;
			}

			transaction.get_cfg ( function () { transaction._send_paypal ( vals, prods, sped ); } );
		}
		vals.inherits ( transaction.cfg, true );
		
		liwe.dom.create_element ( 'div', '_pp_form' );

		//FOR COMPATIBILITY
		var custom = data.custom || String.formatDict ( pp_custom, vals )

		transaction.ajax ( { action: 'transaction.ajax.get_hash', custom: custom }, function ( res )
		{
			vals [ 'custom' ] = custom + '#' + res [ 'hash' ];
			
			vals [ 'shipping_cost' ] = String.formatDict ( "%(total_vat)m", sped ).replace ( ",", "." );

			/*
			var pp_cancel  = liwe.cfg.get ( "modules" + module + "pp_cancel",  transaction.cfg [ 'pp_cancel' ] ); 
			var pp_confirm = liwe.cfg.get ( "modules" + module + "pp_confirm", transaction.cfg [ 'pp_confirm' ] );
			*/
			var pp_cancel  = transaction.cfg [ 'pp_cancel' ];
			var pp_confirm = transaction.cfg [ 'pp_confirm' ];

			vals [ '_cancel' ] = String.formatDict ( pp_cancel, vals ); // transaction.cfg [ 'pp_cancel' ], vals );
			vals [ '_confirm' ] = String.formatDict ( pp_confirm, vals ); // transaction.cfg [ 'pp_confirm' ], vals );
			vals [ '_notyfy' ] = transaction.cfg [ 'pp_notify' ];

			console.log ( vals )

			var s = new String.buffer (); 
			s.add ( String.formatDict ( transaction.templates [ 'pp_form_start' ], vals ) );

			prods.iterate ( function ( v, k )
				{
					prods [ k ] [ '_row_count' ] = parseInt ( k ) + 1;
					prods [ k ] [ '_price' ] =String.formatDict ( "%(price_vat)m", prods [ k ] ).replace ( '.' , '' ).replace ( ',', '.' )
					s.add ( String.formatDict ( transaction.templates [ 'pp_form_row' ], prods [ k ] ) );
				} );

			s.add ( transaction.templates [ 'pp_form_end' ] );

			$( "_pp_form" ).innerHTML = s.toString ();
			$( "_pp_form" ).firstChild.submit ();
			
		} );
		
	} );


	
};
//}}}
transaction._pp_response = function ( pp_resp )
{
	//Controllo che non esisita una chiamata registrata da qualche modulo
	//se non trovo nulla dispaccio l'evento della transaction
	liwe.types.to_dict ( pp_resp );
	transaction.dispatchEvent ( "pp_response", null, pp_resp );
};



//{{{TRNASCTION UNIT TEST UNCOMMENT THIS FOR TRY PAY PAL
transaction._unit_test = function ( dest_div )
{
    var f = new liwe.form.instance ( "pp_send_form" );
    f.text ( { name : "product_code_0" , label : "Articolo" , value : "000" , size : 10 , nonl : true, mandatory : true } );
    f.text ( { name : "descr_0" ,  value : "Articolo 000" , size : 10 , nonl : true, mandatory : true } );
    f.number ( { name : "quant_0", value : "1", size : 5 , nonl : true, mandatory : true } );
    f.money ( { name : "price_vat_0", value : "10000", size : 5  , mandatory : true } );

    f.text ( { name : "product_code_1" , label : "Articolo" , value : "001" , size : 10 , nonl : true, mandatory : true } );
    f.text ( { name : "descr_1" ,  value : "Articolo 001" , size : 10 , nonl : true, mandatory : true } );
    f.number ( { name : "quant_1", value : "1", size : 5 , nonl : true, mandatory : true } );
    f.money ( { name : "price_vat_1", value : "6000", size : 5  , mandatory : true } );

    f.money ( { name : "sped", label : "Spese di spediazione" , size : 5, value : "1000" } );
    f.button ( { value : "paga", onclick : "transaction._unit_test_pay()" } );
    f.set ( dest_div );
}

transaction._unit_test_pay = function ()
{
    var f = liwe.form.get ( "pp_send_form" );
    if ( ! f.check() ) return;


    var prods = [];
    for ( i = 0; i < 2 ; i++ )
    {
        var prod = {};
        [ 'product_code', 'descr', 'quant', 'price_vat' ].iterate ( function ( field )
        {
            key =  String.formatDict ( '%(f)s_%(_id)s' , { f : field, _id : i } );
            prod [ field ] = f.get_value ( key );
        } );
        prods.push ( prod );
    }

    var sped = { 'total_vat' : f.get_value ( 'sped' , 0 ) };
    var vals = { 'order_code' : 'TEST0001', 'cback' : 'abbonamento.ajax.paypal_cback', 'module' : 'abbonamento' };

    transaction.send_paypal ( vals, prods, sped )

}
///}}}

